package com.esender.strategy.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class MobileOperatorUtil {
    private static final String URL = "https://cx.shouji.360.cn/phonearea.php?number=";
    private static final String SPACE = " ";
    private static final String SEPARATOR = ",";
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 获取手机号信息
     * @param mobile 手机号前七位即可
     * @return
     */
    public String getMobileInfo(String mobile){
        String mobileJson = restTemplate.getForObject(URL + mobile, String.class);
        // {"code":0,"data":{"province":"\u4e91\u5357","city":"\u6606\u660e","sp":"\u79fb\u52a8"}}
        Map map = null;
        try {
            map = objectMapper.readValue(mobileJson, Map.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        Integer code = (Integer)map.get("code");
        if (code != 0){
            return null;
        }
        Map<String,String> dataMap = (Map<String,String>)map.get("data");
        // 封装为省 市,运营商  的格式返回
        String province = dataMap.get("province");
        String city = dataMap.get("city");
        String sp = dataMap.get("sp");

        return province + SPACE + city + SEPARATOR + sp;
    }
}
